﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using Company.Project.Application.BaseService;
using Company.Project.Domain.Base;
using Company.Project.Infrastructure.Repository;
using Company.Utility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using Microsoft.IdentityModel.Logging;

namespace Company.Project.Infrastructure.IoC.CoreNative
{
    /// <summary>
    /// 通过反射动态构建依赖注入
    /// </summary>
    public static class IocCoreNativeServiceExtension
    {
        public static IServiceCollection RegisterAssembly(this IServiceCollection service)
        {
            AssemblyHelper.GetAllAssemblies().ForEach(interfaceAssembly =>
            {
                var types = interfaceAssembly.GetTypes().Where(t =>
                    t.GetTypeInfo().IsInterface && !t.GetTypeInfo().IsGenericType &&
                    t.GetInterfaces().Contains(typeof(IDependencyDynamicService)));
                foreach (var type in types)
                {
                    var implementTypeName = type.Name.Substring(1);
                    var implementType = AssemblyHelper.GetImplementType(implementTypeName, type);
                    if (implementType != null)
                    {
                        service.AddScoped(type, implementType);
                    }
                }
            });
            return service;
        }
    }
}
